// pages/modelStore/index.js
import {
  modelApi
} from "../../api/index"
let leftHeight = 0,
  rightHeight = 0; //分别定义左右两边的高度
let query;
const app = getApp()
Page({
  data: {
    IMGBASEURL: app.globalData.IMGBASEURL,
    isFixed: false, //是否吸顶
    navHeadH: 0,
    tagActive: 1,
    listLoadStatus: 0,
    isRenderOver: true,
    list: [],
    leftList: [],
    rightList: [],
    totalPages: 0,
    totalCount: 0,
    tagList: [{
        text: '模型广场',
        val: 1
      },
      {
        text: '名人堂',
        val: 2
      },
    ]
  },
  listPagination: {
    index: 0,
    num: 10,
  },
  // 去搜索
  goSearch() {
    wx.navigateTo({
      url: `/pages/home/search/index?modelType=${this.data.tagActive}`,
    })
  },
  // 去详情
  toDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    // console.log('去详情',item);
    wx.navigateTo({
      url: `/pages/modelStore/modelDetail/index?id=${item.id}`,
    })
  },
  // tag切换
  chlichTap(e) {
    let _this = this
    const index = e.currentTarget.dataset['index']
    let obj = {}
    obj.tagActive = index
    this.setData({
      ...obj
    })
    wx.pageScrollTo({
      scrollTop: 0,
      success() {
        _this.loadData(true)
      }
    })
  },
  // 加载列表
  async loadData(fresh = false) {
    this.setData({
      listLoadStatus: 1
    });
    let pageIndex = this.listPagination.index + 1;
    const pageSize = this.listPagination.num;
    let nextList = []
    // 刷新
    if (fresh) {
      pageIndex = 1;
      this.setData({
        leftList: [],
        rightList: []
      })
    }
    try {
      if (this.data.tagActive === 1) {
        let res = await modelApi.getModelPlaza({
          pageIndex,
          pageSize,
          name: ""
        })
        // console.log('模型广场', res.items);
        nextList = this.formateData(res.items)
        // nextList = res.items
        // console.log('nextList',nextList);
        this.setData({
          listLoadStatus: this.data.list.length == res.totalCount ? 2 : 0,
        });
      } else {
        let res = await modelApi.getModelHOF({
          pageIndex,
          pageSize,
          name: ""
        })
        // console.log('名人堂', res);
        nextList = this.formateData(res.items)
        // nextList = res.items
        this.setData({
          listLoadStatus: this.data.list.length == res.totalCount ? 2 : 0,
        });
      }
      this.setData({
        list: fresh ? nextList : this.data.list.concat(nextList),
      });
      const {
        leftList,
        rightList
      } = this.data;
      query = wx.createSelectorQuery().in(this);
      for (let index = 0; index < nextList.length; index++) {
        if (index == 0) {
          this.data.isRenderOver = false
        }
        const item = nextList[index];
        if (this.data.listLoadStatus == 1) {
          this.data.isRenderOver = true
          return
        }
        if (this.data.leftList.length === 0 && this.data.rightList.length === 0) {
          leftList.push(item)
        } else {
          leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
        }
        await this.getBoxHeight(leftList, rightList);
        if (index == nextList.length - 1) {
          this.data.isRenderOver = true
        }
        if (fresh) {
          wx.stopPullDownRefresh();
        }
      }
      this.listPagination.index = pageIndex;
      this.listPagination.num = pageSize;
    } catch (error) {
      console.log(error);
      this.setData({
        listLoadStatus: 3
      });
    }
  },
  // 处理数据
  formateData(items) {
    items.forEach((item, index) => {
      item['showTags'] = [] //用于tag展示
      let arr3 = item.tags.filter(tag => tag.length <= 3)
      let arr4 = item.tags.filter(tag => tag.length > 3)
      // 先用三个字以内的，3个字没有才用4个字的
      if (arr3.length && arr3.length >= 3) {
        item.showTags = arr3.slice(0, 3)
      } else if (arr3.length && arr3.length < 3) {
        if (arr3.length > 1) {
          arr3.push('...')
          item.showTags = arr3
        }else{
          item.showTags = arr3
        }
      } else {
        if (arr4.length && arr4.length > 1) {
          item.showTags = arr4.slice(0, 1)
          item.showTags.push('...')
        } else {
          item.showTags = arr4
        }
      }
      // console.log('showTags', item.showTags);
    })

    return items
  },
  //获取左右两边高度
  getBoxHeight(leftList, rightList) {
    return new Promise((resolve, reject) => {
      this.setData({
        leftList,
        rightList
      }, () => {
        query.select('#left').boundingClientRect();
        query.select('#right').boundingClientRect();
        query.exec((res) => {
          setTimeout(() => {
            leftHeight = res[0].height; //获取左边列表的高度
            rightHeight = res[1].height; //获取右边列表的高度
            resolve();
          }, 0)
        });
      });
    })
  },
  onReTry() {
    this.loadData(true);
  },
  onReady() {
    wx.createSelectorQuery().select("#tabsId").boundingClientRect((rect) => {
      if (rect && rect.height) {
        this.setData({
          navHeadH: parseInt(rect.height)
        })
      }
    }).exec()
    this.loadData()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // console.log('下拉刷新');
    if (this.data.listLoadStatus === 0 && this.data.isRenderOver) {
      this.loadData(true)
    } else {
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // console.log('触底');
    if (this.data.listLoadStatus === 0 && this.data.isRenderOver) {
      this.loadData();
    }
  },
  onShow() {
    this.getTabBar().init();
  },
})